<?php

declare(strict_types=1);

namespace App\Controller\AdminApi;

use App\Exception\XZXValidationException;
use App\Middleware\AdminApi\AdminJWTAuthMiddleware;
use App\Service\MchSysAdminService;
use App\Utils\CustomUtils;
use App\Utils\DateUtils;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use App\Constants\XZXResponseCode;

/**
 * Class MchSysAdminController
 * @package App\Controller
 *
 * @Controller(prefix="/admin/api/mchSysAdmin")
 */
class MchSysAdminController extends AdminBaseController
{
    /**
     * @Inject()
     * @var ValidatorFactoryInterface
     */
    protected $validationFactory;

    /**
     * @Inject()
     * @var MchSysAdminService
     */
    protected $MchSysAdminService;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    public function __construct(LoggerFactory $loggerFactory)
    {
        // 第一个参数对应日志的 name, 第二个参数对应 config/autoload/logger.php 内的 key
        $this->logger = $loggerFactory->get('log', 'default');
    }

    /**
     * 查看
     * @PostMapping(path = "get")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function get(RequestInterface $request)
    {
        // $validator = $this->validationFactory->make(
        //     $request->all(),
        //     [
        //         'id' => 'required|uuid',
        //     ],
        // );

        // if ($validator->fails()){
        //     // Handle exception
        //     $errorMessage = $validator->errors()->first();  
        //     throw new XZXValidationException($errorMessage);
        // }

        // $param = $request->all();
        // return $this->MchSysAdminService->get($param);
    }

    /**
     * 编辑
     * @PostMapping(path = "edit")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function edit(RequestInterface $request)
    {

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id'              => 'required|uuid',
                'password'        => 'sometimes|required|between:5,16|alpha_dash|confirmed',
                'password_confirmation ' =>  'sometimes|required|between:5,16|alpha_dash',                
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        // $param['from'] = 'platform';
        $param['source'] = 2;        
        return $this->MchSysAdminService->edit($param);
    }

    /**
     * 添加
     * @PostMapping(path = "add")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function add(RequestInterface $request)
    {

        // $validator = $this->validationFactory->make(
        //     $request->all(),
        //     [
        //         //'desciption' => 'required',
        //         //'name' => 'required',
        //     ],
        // );

        // if ($validator->fails()){
        //     // Handle exception
        //     $errorMessage = $validator->errors()->first();  
        //     throw new XZXValidationException($errorMessage);
        // }

        // $param = $request->all();
        // return $this->MchSysAdminService->add($param);
    }

    /**
     * 删除
     * @PostMapping(path = "del")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function del(RequestInterface $request)
    {

        // $validator = $this->validationFactory->make(
        //     $request->all(),
        //     [
        //         'id' => 'required',
        //     ],
        // );

        // if ($validator->fails()){
        //     // Handle exception
        //     $errorMessage = $validator->errors()->first();  
        //     throw new XZXValidationException($errorMessage);
        // }

        // $param = $request->all();
        // return $this->MchSysAdminService->del($param);
    }

    /**
     * 查询
     * @PostMapping(path = "list")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function list(RequestInterface $request)
    {

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'page'               => 'required|integer|min:1',
                'limit'              => 'required|integer|min:1',
                // 'search.email'       => 'sometimes|required|email',
                'search.roleId'      => 'sometimes|required|uuid',
                'search.status'      => 'sometimes|required|integer|max:1|min:0',                
                // 'search.username' => 'sometimes|required|between:4,8|alpha_num',              
                'search.mchNo'       => 'sometimes|required|between:5,8',  
                'search.mchName'       => 'sometimes|required|between:3,8|alpha_num',                
            ]
        );

        

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }
        
        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        (!$ext['isSuperRole'] && isset($ext['mchIdList']) && !empty($ext['mchIdList'])) && $param['mchIdList'] = $ext['mchIdList'];

        if(isset($param['search'])){
            $search = $param['search'];        
            CustomUtils::xzxAddSearch($param, $search, 'mchName');
            CustomUtils::xzxAddSearch($param, $search, 'mchNo');
            CustomUtils::xzxAddSearch($param, $search, 'status');
            CustomUtils::xzxAddSearch($param, $search, 'roleId');
            CustomUtils::xzxAddSearch($param, $search, 'createTimeRange');
            if(isset($param["createTimeRange"]))
            {
                try {
                    $param['createTimeRange'][0] = DateUtils::dateToTimeStamp($param['createTimeRange'][0]);
                    $param['createTimeRange'][1] = DateUtils::dateToTimeStamp($param['createTimeRange'][1]);
                } catch (\Throwable $th) {
                    unset($param['createTimeRange']);
                }
            }
        }
                
        return $this->MchSysAdminService->list($param);
    }

    /**
     * 重置google密钥
     * @PostMapping(path = "resetGoogleAuthSecret")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */ 
    public function resetGoogleAuthSecret(RequestInterface $request) {

        // $param['id'] = trim($request->post('id'));
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'mchId'              => 'required|uuid',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $param['source'] = 2;  
        return $this->MchSysAdminService->resetGoogleAuthSecret($param);
    }

    /**
     * 重置商户默认超级管理员密码
     * @PostMapping(path = "changePassword")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function changePassword(RequestInterface $request)
    {

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'mchId'              => 'required|uuid',
                'password'        => 'required|between:5,16|alpha_dash|confirmed',
                'password_confirmation' =>  'required|between:5,16|alpha_dash',                
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['isSuperRole'] = $ext['isSuperRole'];
        if (!$param['isSuperRole']) {
            $param['mchIdList'] = $ext['mchIdList'];
            if (!in_array($param['mchId'], $param['mchIdList'])) {
                throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::NO_PERMISSION_TO_OPERATE));
            }
        }
        $param['source'] = 2;        
        return $this->MchSysAdminService->edit($param);
    }    
   
}